package dj.action.base;

import java.io.PrintWriter;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.ParentPackage;

import com.google.gson.GsonBuilder;

@ParentPackage("basePackage")
public class BaseAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(BaseAction.class);

	protected void writeToJson(Object obj) {
		writeToJson(obj, "yyyy-MM-dd HH:mm:ss");
	}

	protected void writeToJson(Object obj, String dateFormat) {

		try {
			String json = new GsonBuilder().setDateFormat(dateFormat).create().toJson(obj);

			ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
			ServletActionContext.getResponse().setContentType("text/plain; charset=UTF-8");
			ServletActionContext.getResponse().setHeader("Cache-Control", "no-cache");
			PrintWriter out = ServletActionContext.getResponse().getWriter();
			out.print(json);
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
	}

}
